package com.xiaochi.subject.domain.service.impl;/**
 * @author zqx
 * @since 2024/7/20
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.xiaochi.subject.common.enums.CategoryTypeEnum;
import com.xiaochi.subject.common.enums.IsDeletedEnum;
import com.xiaochi.subject.domain.convert.SubjectCategoryConverter;
import com.xiaochi.subject.domain.convert.SubjectInfoConverter;
import com.xiaochi.subject.domain.convert.SubjectLabelConverter;
import com.xiaochi.subject.domain.entity.SubjectCategoryBO;
import com.xiaochi.subject.domain.entity.SubjectLabelBO;
import com.xiaochi.subject.domain.service.SubjectCategoryDomainService;
import com.xiaochi.subject.domain.utli.CacheUtil;
import com.xiaochi.subject.infra.basic.entity.SubjectCategory;
import com.xiaochi.subject.infra.basic.entity.SubjectLabel;
import com.xiaochi.subject.infra.basic.entity.SubjectMapping;
import com.xiaochi.subject.infra.basic.service.SubjectCategoryService;
import com.xiaochi.subject.infra.basic.service.SubjectLabelService;
import com.xiaochi.subject.infra.basic.service.SubjectMappingService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.stream.Collectors;

/**
 * @author zqx
 * @since
 */
@Service
@Slf4j
public class SubjectCatagoryDomainServiceImpl implements SubjectCategoryDomainService {

    @Resource
    private SubjectCategoryService subjectCategoryService;
    
    @Resource
    private SubjectMappingService  subjectMappingService;

    @Resource
    private SubjectLabelService subjectLabelService;

    @Resource
    private ThreadPoolExecutor labelThreaPool;

    @Resource
    private CacheUtil cacheUtil;


    @Override
    public void add(SubjectCategoryBO subjectCategoryBO) {
        if(log.isInfoEnabled()){
            log.info("SubjectCatagoryDomainServiceImpl.add.bo:{}", JSON.toJSONString(subjectCategoryBO));
        }
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.CategoryBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedEnum.UN_DELETED_ENUM.getCode());
        subjectCategoryService.insert(subjectCategory);
    }

    @Override
    public List<SubjectCategoryBO> queryCategory(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.CategoryBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedEnum.UN_DELETED_ENUM.getCode());
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        //转成bo
        List<SubjectCategoryBO> subjectCategoryBOList = SubjectCategoryConverter.INSTANCE.CategoryListToCategoryBoList(subjectCategoryList);
        if(log.isInfoEnabled()){
            log.info("SubjectCatagoryDomainServiceImpl.queryCategory.subjectCategoryBOList:{}",
                    JSON.toJSONString(subjectCategoryBOList));
        }
        subjectCategoryBOList.forEach(bo -> {
            Integer count = subjectCategoryService.queryBySubjectCount(bo.getId());
            bo.setCount(count);
        });
        return subjectCategoryBOList;
    }

    @Override
    public Boolean update(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.CategoryBoToCategory(subjectCategoryBO);
        SubjectCategory update = subjectCategoryService.update(subjectCategory);
        return ObjectUtils.isNotEmpty(update);
    }

    @Override
    public Boolean deleted(SubjectCategoryBO subjectCategoryBO) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.CategoryBoToCategory(subjectCategoryBO);
        subjectCategory.setIsDeleted(IsDeletedEnum.DELETED_ENUM.getCode());
        SubjectCategory update = subjectCategoryService.update(subjectCategory);
        return ObjectUtils.isNotEmpty(update);
    }


    @Override
    @SneakyThrows
    public List<SubjectCategoryBO> queryCategoryAndLabel(SubjectCategoryBO subjectCategoryBO) {
        Long id = subjectCategoryBO.getId();
        String cacheKey = "categoryAndLabel." + subjectCategoryBO.getId();
        List<SubjectCategoryBO>  subjectCategoryBOS = cacheUtil.getResult(cacheKey,SubjectCategoryBO.class,
                (key) -> getSubjectCategoryBOS(id));
        return subjectCategoryBOS;
    }

    @SneakyThrows
    private List<SubjectCategoryBO> getSubjectCategoryBOS(Long categoryId) {
        //查询大类 分类下的
        SubjectCategory subjectCategory = new SubjectCategory();
        subjectCategory.setParentId(categoryId);
        subjectCategory.setIsDeleted(IsDeletedEnum.UN_DELETED_ENUM.getCode());
        List<SubjectCategory> subjectCategorieList = subjectCategoryService.queryCategory(subjectCategory);
        if(log.isInfoEnabled()){
            log.info("SubjectCatagoryDomainServiceImpl.queryCategoryAndLabel.subjectCategorieList:{}",
                    JSON.toJSONString(subjectCategorieList));
        }
        //一次获取到标签信息
        List<SubjectCategoryBO> subjectCategoryBOList = SubjectCategoryConverter.INSTANCE.CategoryListToCategoryBoList(subjectCategorieList);
        List<CompletableFuture<Map<Long, List<SubjectLabelBO>>>> futureList = subjectCategoryBOList.stream().map(categoryBo ->
                CompletableFuture.supplyAsync(() -> getLabelBOList(categoryBo), labelThreaPool)
        ).collect(Collectors.toList());
        Map<Long,List<SubjectLabelBO>> map = new HashMap<>();
        //todo 想知道foreach 和 增强for有什么区别
//        futureList.forEach(future -> {
//            try {
//                Map<Long, List<SubjectLabelBO>> longListMap1 = future.get();
//                map.putAll(longListMap1);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        });
        for (CompletableFuture<Map<Long, List<SubjectLabelBO>>> future : futureList) {
            Map<Long, List<SubjectLabelBO>> longListMap = future.get();
            map.putAll(longListMap);
        }
        subjectCategoryBOList.forEach(categoryBO -> {
            categoryBO.setLabelBOList(map.get(categoryBO.getId()));
        });
        return subjectCategoryBOList;
    }

    private Map<Long,List<SubjectLabelBO>> getLabelBOList(SubjectCategoryBO categoryBO) {
        Map<Long,List<SubjectLabelBO>> labelMap =new HashMap<>();
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setCategoryId(categoryBO.getId());
        subjectMapping.setIsDeleted(IsDeletedEnum.UN_DELETED_ENUM.getCode());
        List<SubjectMapping> subjectMappingList = subjectMappingService.queryLabelId(subjectMapping);
        if (CollectionUtils.isEmpty(subjectMappingList)){
            return null;
        }
        List<Long> labelIdList = subjectMappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        List<SubjectLabel> labelList = subjectLabelService.batchQueryById(labelIdList);
        List<SubjectLabelBO> boList = SubjectLabelConverter.INSTANCE.convertLabelToBoList(labelList);
        labelMap.put(categoryBO.getId(),boList);
        return labelMap;
    }
}
